let clubMemberDao = require('../dao/ClubMemberDao');
let clubInfoDao = require('../dao/ClubInfoDao');
let userDao = require('../dao/userDao')
let mysqlPool = require('../dao/MySQLPool');
let tokenService = require('../service/TokenService')
let cconst = require('../const')
let userService = require('../service/userService');

let unionInfoDao = require('../dao/UnionInfoDao');

const {BusiError} = require('../exception/exception');

class ClubMemberService{
    constructor() {
        
    }

    async updateBuffer(clubID, uid, buffer){
        let m = await clubMemberDao.getByUID(uid, clubID);
        if(!m){
            console.logw("俱乐部成员不存在:", clubID, uid, buffer);
            throw new BusiError(500, "俱乐部成员不存在");
        }

        let res = await clubMemberDao.upateBuffer(uid, clubID, buffer);
        if(res <= 0){
            console.logw("俱乐部更新buffer失败:", clubID, uid, buffer);
            throw new BusiError(500, "更新buffer失败");
        }

        console.logw("俱乐部更新buffer成功:", clubID, uid, buffer);
    }


    async saveClub(club){
        await clubMemberDao.saveClub(club);
    }

    async createClub(uid, clubName){
        let user = {uid : uid}
        let result = await userDao.getUserByCondition(user);
        if(!user && user.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        user = result[0];
        let club_info = await clubInfoDao.getByName(clubName);
        if(club_info){
            throw new BusiError(500, "俱乐部名字已存在");
        }
        let rand = Math.random()*100000000;
        let clubId =  parseInt(rand);
        let clubinfo = {
            clubId: clubId,
            setting: "",
            ownerUid: uid,
            ownerName: user.name,
            ownerUrl: user.headimgurl,
            clubName: clubName,
            rel: 0,
            clubCard: 0,
            create_time: new Date()
        }

        let club = {
            clubId: clubId,
            ownerUid: uid,
            ownerName: user.name,
            clubName: clubName,
            headimgurl: user.headimgurl,
            createTick: new Date().getTime(),
            memberUid: uid,
            agree: 1,
            joinTick: 0,
            memberImgurl: user.headimgurl,
            memberName: user.name,
            typeName: '',
            create_time: new Date(),
            join_time: new Date(),
            coins: 0,
            buffer: 0
        }

        await mysqlPool.doWithTx(async function (conn) {
            await clubInfoDao.saveClubInfoWithTx(clubinfo, conn);
            await clubMemberDao.saveClubWithTx(club, conn);
        });
        return clubinfo;
    }

    async joinClub(uid, clubId){
        let user = {uid : uid}
        let result = await userDao.getUserByCondition(user);
        if(!result && result.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        user = result[0];
        let clubinfo = await clubInfoDao.getByClubID(clubId);
        if(!clubinfo){
            throw new BusiError(500, "俱乐部不存在 id是 " + clubId);
        }
        let member = await clubMemberDao.getByClubIdAndUid(uid, clubId);

        if(member && member.agree >= 0){
            throw new BusiError(500, "已申请过该俱乐部");
        }
        if(member && member.agree < 0){
            await clubMemberDao.updateAgree(clubId, uid, 0);
            return clubinfo;
        }


        let club = {
            clubId: clubId,
            ownerUid: clubinfo.ownerUid,
            ownerName: clubinfo.ownerName,
            clubName: clubinfo.clubName,
            headimgurl: clubinfo.ownerUrl,
            createTick: new Date().getTime(),
            memberUid: uid,
            agree: 0,
            joinTick: 0,
            memberImgurl: user.headimgurl,
            memberName: user.name,
            typeName: '',
            create_time: new Date(),
            join_time: new Date(),
            coins: 0,
            buffer: 0
        }
        await clubMemberDao.saveClubWithTx(club);
        return clubinfo;
    }

    async agentJoinClub(uid, ldUid, level,clubId){
        let user = {uid : uid}
        let result = await userDao.getUserByCondition(user);
        if(!result && result.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        user = result[0];
        let clubinfo = await clubInfoDao.getByClubID(clubId);
        if(!clubinfo){
            throw new BusiError(500, "俱乐部不存在 id是 " + clubId);
        }
        let member = await clubMemberDao.getByClubIdAndUid(uid, clubId);

        if(member && member.agree >= 0){
            throw new BusiError(500, "已申请过该俱乐部");
        }
        // if(member && member.agree < 0){
        //     await clubMemberDao.updateAgree(clubId, uid, 0);
        //     return clubinfo;
        // }


        let club = {
            clubId: clubId,
            ownerUid: clubinfo.ownerUid,
            ownerName: clubinfo.ownerName,
            clubName: clubinfo.clubName,
            headimgurl: clubinfo.ownerUrl,
            createTick: new Date().getTime(),
            memberUid: uid,
            agree: 1,
            joinTick: 0,
            memberImgurl: user.headimgurl,
            memberName: user.name,
            typeName: '',
            create_time: new Date(),
            join_time: new Date(),
            coins: 0,
            buffer: 0,
            agentLevel:level,
            agentLeader:ldUid,
            agentJoinTime:new Date()
        }
        await clubMemberDao.saveClubWithTxAgent(club);
        return clubinfo;
    }

    async dissolveClub(uid, clubId){
        let user = {uid : uid};
        let result = await userDao.getUserByCondition(user);
        if(!result && result.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        user = result[0];
        let clubinfo = await clubInfoDao.getByClubID(clubId);
        if(!clubinfo){
            throw new BusiError(500, "俱乐部不存在");
        }
        if(clubinfo.ownerUid !== uid){
            throw new BusiError(500, "用户无权限");
        }

        await mysqlPool.doWithTx(async (conn) => {
            let flag = await clubInfoDao.judgeClubDissolveAble(clubId, mysqlPool);
            if(!flag){
                throw new BusiError(500, "俱乐部疲劳值没有清空，无法解散");
            }
            await clubInfoDao.dissolveClub(clubId, mysqlPool);
        });


    }

    async quitClub(uid, clubId){
        let user = {uid : uid};
        let result = await userDao.getUserByCondition(user);
        if(!result && result.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        let clubinfo = await clubInfoDao.getByClubID(clubId);
        if(!clubinfo){
            throw new BusiError(500, "俱乐部不存在");
        }
        let member = await  userDao.getClubMemberById(clubId, uid);
        if(member.unionCoin !== 0 && member.unionCoin !== null){
            throw new BusiError(500, "用户疲劳币没有结清，不能退出");
        }
        if(member.coins !== 0 && member.coins !== null){
            throw new BusiError(500, "用户金币豆没有结清，不能退出");
        }

        await clubMemberDao.quitClub(uid, clubId);
    }

    async updateClubRoyaltySetting_bug(uid, clubId, data){
        let user = {uid : uid};
        let result = await userDao.getUserByCondition(user);
        if(!result && result.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        let clubinfo = await clubInfoDao.getByClubID(clubId);
        if(!clubinfo){
            throw new BusiError(500, "俱乐部不存在");
        }
        if(clubinfo.ownerUid !== uid){
            throw new BusiError(500, "用户无权限");
        }
        await  clubInfoDao.updateClubRoyaltySetting(clubId, data);
    }

    async updateClubRoyaltySetting(uid, clubId, data){
        let user = {uid : uid};
        let result = await userDao.getUserByCondition(user);
        if(!result && result.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        let clubinfo = await clubInfoDao.getByClubID(clubId);
        if(!clubinfo){
            throw new BusiError(500, "俱乐部不存在");
        }
        if(clubinfo.ownerUid != uid){
            throw new BusiError(500, "用户无权限");
        }
        var royaltySetting={}
        if(clubinfo.royaltySetting)
        {
            royaltySetting=JSON.parse(clubinfo.royaltySetting)
        }
        if(typeof data=="string")
        {
            console.log("更新设置 ",data);
            data=JSON.parse(data);
        }
        for(var  k in data)
        {
            if(data[k]==undefined)  continue;
            royaltySetting[k]=data[k]
        }
        var  s=JSON.stringify(royaltySetting);
        await  clubInfoDao.updateClubRoyaltySetting(clubId, s);
    }

    async getClubInfo(uid, clubId){
        let user = {uid : uid};
        let result = await userDao.getUserByCondition(user);
        if(!result && result.length === 0){
            throw  new BusiError(500, "用户不存在");
        }
        user = result[0];
        let clubinfo = await clubInfoDao.getByClubID(clubId);
        if(!clubinfo){
            throw new BusiError(500, "俱乐部不存在");
        }
        return await  clubInfoDao.getClubInfo(clubId);

    }

    /*async saveClubRoyaltyRecord(recordList){
        if(recordList.length === 0){
            return;
        }
        let memberList = [];
        memberList.push(recordList[0]);
        for(let i =1 ; i< recordList.length; i++){
            let r = recordList[i];
            if(r.winScore > memberList[0].winScore){
                memberList = [];
                memberList.push(r);
            }else if(r.winScore === memberList[0].winScore){
                memberList.push(r);
            }
        }
        let clubId = memberList[0].clubID;
        let clubInfo = await clubInfoDao.getByClubID(clubId);
        let totalAmount = memberList[0].winScore;
        if(totalAmount <= 0){
            return;
        }
        let royaltyRate = 10;
        let gameType = memberList[0].gameType;
        if(clubInfo.royaltySetting ){
            let royaltySetting = JSON.parse(clubInfo.royaltySetting);
            if(royaltySetting[gameType] !== undefined){
                royaltyRate = royaltySetting[gameType];
            }
        }
        let royaltyAmount = parseInt(totalAmount*royaltyRate/100);
        for(let i =0 ; i< memberList.length; i++){
            let loyaltyRecord = {
                clubId: clubId,
                memberUid: memberList[i].uid,
                totalAmount: totalAmount,
                royaltyRate: royaltyRate,
                royaltyAmount: royaltyAmount,
                roomId: memberList[i].roomID,
                gameType: gameType
            };
            await clubInfoDao.saveClubRoyaltyRecord(loyaltyRecord);
        }
    }*/
    async saveClubRoyaltyRecord(recordList){

        //获取需要进行抽水的玩家列表
        let memberList =  this.getWinnerList2(recordList);
        if(memberList.length === 0){
            return;
        }

        let clubId = memberList[0].clubID;
        let clubInfo = await clubInfoDao.getByClubID(clubId);

        let gameType = memberList[0].gameType;
        let gameTypeChild = memberList[0].gameTypeChild;
        if (gameTypeChild && gameTypeChild != ""){
            gameType = gameTypeChild;
        }

        //对不同排名的玩家进行抽水
        for(let i =0 ; i< memberList.length; i++){
            let totalAmount = memberList[i].winScore;
            if(totalAmount <= 0){
                return;
            }
            let royaltyRate = cconst.sys_default_royalty_rate;
            if(clubInfo.royaltySetting ){
                let royaltySetting = JSON.parse(clubInfo.royaltySetting);
                if(royaltySetting[gameType] !== undefined && royaltySetting[gameType][memberList[i].sort] !== undefined){
                    royaltyRate = royaltySetting[gameType][memberList[i].sort];
                }
            }
            let royaltyAmount = parseInt(totalAmount*royaltyRate/100);
            let loyaltyRecord = {
                clubId: clubId,
                memberUid: memberList[i].uid,
                totalAmount: totalAmount,
                royaltyRate: royaltyRate,
                royaltyAmount: royaltyAmount,
                roomId: memberList[i].roomID,
                gameType: gameType,
                gameSort: memberList[i].sort,
                roomTs:memberList[i].roomTs,
            };
            await clubInfoDao.saveClubRoyaltyRecord(loyaltyRecord);
            console.log("my club 抽水扣钱!",royaltyAmount)
            await userService.updateCoins(clubId, 1, memberList[i].uid, gameType, -royaltyAmount, memberList[i].roomID, "");
        }
    }

    keysort(key,sortType){
        return function(a,b){
            return sortType ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
        }
    }
    getWinnerList2(recordList){
        //先筛选出比赛前3名分数
        let memberList = [];
        let curscore = 0;
        let level = 0;
        recordList.sort(this.keysort('winScore',true));
        for(let i = 0 ; i< recordList.length; i++){
            let r = recordList[i];
            if(r.winScore <= 0 ){
                break;
            }

            if (curscore!==r.winScore){
                curscore = r.winScore;
                level=level+1;
                if (level>3){
                    break;
                }
                r.sort=level;
                memberList.push(r);
            }else{
                r.sort=level;
                memberList.push(r);
            }

        }
        return memberList;
    }

    //获取需要进行抽水的玩家列表
    getWinnerList(recordList){
        //先筛选出比赛前3名分数
        let memberList = [];
        let record1 = null;
        let record2 = null ,record3 = null;
        let records =  [];
        for(let i = 0 ; i< recordList.length; i++){
            let r = recordList[i];
            if(r.winScore <= 0 ){
                continue;
            }

            if(!record1 || r.winScore > record1.winScore){
                if(record1){
                    record2 = record1;
                    records["2"] = record2;
                }
                record1 = r;
                records["1"] = record1;
            }else if(!record2 || r.winScore > record2.winScore){
                if(record2){
                    record3 = record2;
                    records["3"] = record3;
                }
                record2 = r;
                records["2"] = record2;
            }else if(!record3 || r.winScore > record3.winScore){
                record3 = r;
                records["3"] = record3;
            }
        }
        for(let i in records) {
            for(let j in recordList){
                let r = recordList[j];
                if(r.winScore <= 0 ){
                    continue;
                }
                if(r.winScore === records[i].winScore){
                    r.sort = i;
                    memberList.push(r);
                }
            }
        }
        return memberList;
    }

    async getClubRoyaltyRecordList(date, clubId){
        let startTime = new Date(date);
        let endTime = new Date(startTime.getTime() + 24 * 60 * 60 *1000);
 //       return await clubInfoDao.getClubRoyaltyRecordList(clubId, startTime, endTime);
        let res = await clubInfoDao.getClubRoyaltyRecordList(clubId, startTime, endTime);
        return await unionInfoDao.pakageClubRoyaltyRecord(res);
    }

}



let clubMemberService = new ClubMemberService();
module.exports = clubMemberService;